﻿using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.HtmlTemplate.Pdf.HtmlPaster
{
    public class HtmlByRazorTemplateExporter: IHtmlByRazorTemplateExporter
    {
        public HtmlByRazorTemplateExporter()
        {
            var config = new TemplateServiceConfiguration();
            //config.ReferenceResolver = null;
          
            var razorEngineService = RazorEngineService.Create(config);
            Engine.Razor = razorEngineService;
        }
        public Task<string> ExportHtmlByRazorTemplateAsync<T>(T data, string htmlTemplate) where T : class
        {
            var result = RunCompileRazorTemplate(data, htmlTemplate);
            return Task.FromResult(result);
        }
        public string ExportHtmlByRazorTemplate<T>(T data, string htmlTemplate) where T : class
        {
            var result = RunCompileRazorTemplate(data, htmlTemplate);
            return result;
        }

        protected string RunCompileRazorTemplate(object model,string razorTemplateStr)
        {
            if(string.IsNullOrWhiteSpace(razorTemplateStr))
                throw new ArgumentException("Razor模版不能为空");

            var htmlString= Engine.Razor.RunCompile(razorTemplateStr, razorTemplateStr.GetHashCode().ToString(), null, model);
            return htmlString;
        }
    }
}
